//
//  LXTypeView.m
//  cat
//
//  Created by imera on 16/1/19.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "LXTypeView.h"

@interface LXTypeView()
/** 栏目头标题 */
@property (nonatomic, strong) NSArray *titleArray;
/** icon字典 */
@property (nonatomic, strong) NSDictionary *iconDict;
@end

@implementation LXTypeView
- (NSArray *)titleArray
{
    if (_titleArray == nil) {
        _titleArray = @[@"动画",@"娱乐",@"科技",@"电视剧",@"舞蹈",@"音乐",@"游戏",@"海贼王",@"电影"];
    }
    return _titleArray;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        //加载icon文件
        NSString *path = [[NSBundle mainBundle]pathForResource:@"icon" ofType:@"plist"];
        self.iconDict = [NSDictionary dictionaryWithContentsOfFile:path];
        
        [self initSubViews];
    
    }
    return self;
}

- (void)initSubViews
{
    int count = (int)self.titleArray.count;
    int margin = 40;
    int cols = 3;
    CGFloat btnW = (self.frame.size.width - (cols + 1) * margin) / cols;
    CGFloat btnH = btnW;
    for (int i=0; i<count; i++) {
        //分类图标
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        NSString *imageName = self.iconDict[self.titleArray[i]];
        NSString *imageHighlighted = [imageName stringByReplacingOccurrencesOfString:@"t" withString:@"t-on"];
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:imageHighlighted] forState:UIControlStateHighlighted];
        
        CGFloat btnX = margin + (i % cols) * (margin + btnW);
        CGFloat btnY = (i / cols) * (margin + btnH) + margin * 1.5;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        
        NSString *path = [[NSBundle mainBundle]pathForResource:@"category" ofType:@"plist"];
        NSDictionary *typeID = [NSDictionary dictionaryWithContentsOfFile:path];
        btn.tag = [typeID[self.titleArray[i]] integerValue];
        
        [btn addTarget:self action:@selector(cellClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:btn];
        
        //分类文字
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = self.titleArray[i];
        titleLabel.frame = CGRectMake(btnX, btnY + btnH, btnW, 30);
        [self addSubview:titleLabel];
        
    }
}

- (void)cellClick:(UIButton *)btn
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"typeCellClick" object:nil userInfo:@{@"typeID":@(btn.tag)}];
}

@end
